#include "VarTable.h"
#include <regex>

VarTable::VarTable()
{
	this->curr_index = -1;
}

VarTable::~VarTable()
{
	std::map<VARINDEX, VarInfo*>::const_iterator it;

	for (it = index_table.begin(); it != index_table.end(); ++it)
	{
		VarInfo* v = it->second;
		delete v;
		v = NULL;
	}

	//index_table.clear();
}

VARINDEX VarTable::InsertVar(const STRING var_name)
{
	tr1::regex rx("[A-Za-z](([A-Za-z])|([0-9])|(#))*");

	// Check if variable already exist in VarTable.
	VARINDEX var_idx = this->GetVarIndex(var_name);

	if (var_idx == -1 && regex_match(var_name.begin(), var_name.end(), rx))
	{
		this->curr_index++; //next index

		VarInfo* var = new VarInfo;
		var->var_index = this->curr_index;
		var->var_name = var_name;
		var->var_type = INT_TYPE;

		this->index_table.insert(std::pair<VARINDEX, VarInfo*>(this->curr_index,var));
		this->name_table.insert(std::pair<STRING, VarInfo*>(var_name,var));

		var_index_array.insert(curr_index);
		return this->curr_index;
	} else
	{
		return var_idx;
	}
}

STRING VarTable::GetVarName(const VARINDEX index)
{
	if (index >= 0 && index <= this->curr_index)
	{
		int has_var_name = this->index_table.count(index);
		if (has_var_name == 1)
		{
			VarInfo* v = this->index_table.find(index)->second;
			return v->var_name;
		}
	}

	return "";
}

VARINDEX VarTable::GetVarIndex(const STRING var_name)
{

	int has_var_name = this->name_table.count(var_name);
	
	if (has_var_name == 1)
	{
		return this->name_table.find(var_name)->second->var_index;
	}

	return -1;
}

STRING_ARRAY VarTable::GetAllVarNames()
{
	STRING_ARRAY string_array;

	for (VARINDEX i = 0; i <= this->curr_index; i++)
	{
		STRING var_name = this->GetVarName(i);
		string_array.insert(var_name);
	}

	return string_array;
}

VARINDEX_ARRAY VarTable::GetAllVarIndex()
{
	return var_index_array;
}

INTEGER VarTable::GetVarCount()
{
	return var_index_array.size();
}